package com.cj.ctyl.common;


import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Author: Alex
 * @Description: md5加密 加盐加密
 * @Date: 2021/8/14
 */
public class Md5SaltUtils {

    /**
     * 生成md5+salt
     */
    public static Map<String, String> getMD5Encryption(String password, String salt) {
        String md5 = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
        Map<String, String> map = new HashMap<>();
        map.put("md5", md5);
        map.put("salt", salt);
        return map;
    }

    public static Map<String, String> getMD5Encryption(String password) {
        String salt = getSalt();
        return Md5SaltUtils.getMD5Encryption(password, salt);
    }

    /**
     * 生成随机盐
     */
    public static String getSalt() {
        String str = "zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP1234567890";
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 9; i++) {
            int number = random.nextInt(62);
            stringBuffer.append(str.charAt(number));
        }
        return stringBuffer.toString();
    }

    /**
     * 比对加密内容
     */
    public static Boolean comparison(String password, String md5Salt, String salt) {
        if (md5Salt.equals(Md5SaltUtils.getMD5Encryption(password, salt).get("md5"))) {
            return true;
        }
        return false;
    }

}
